#coding:utf-8

from elasticsearch import Elasticsearch
import datetime
import json

class EsDocumentStore(object):

    def __init__(self,prop):
        self.es = Elasticsearch(hosts=[{'host':prop['HOST'],'port':prop['PORT']}])
        self.index = prop['INDEX']
        self.type = prop['TYPE']

    def get(self, i, fields='*'):
        index_name = self.index
        res = self.es.get(index=index_name,doc_type=self.type,id=i,_source_include=fields)
        return res['_source']

    def getTitle(self,i):
        index_name = self.index
        fields=['title']
        res = self.es.get(index=index_name,doc_type=self.type,id=i,_source_include=fields)
        return res['_source']['title']
       

    def getTime(self, st, et, fields='*'):
        T1 = st.strftime('%Y-%m-%d %H:%M:%S')
        T2 = et.strftime('%Y-%m-%d %H:%M:%S')
        q1 = {'range':{
            'create_time':{
                "from": T1,
                "to": T2
            }
        }}
        q = {"query":{
            "bool": {
                "must":[q1]
            }
        }}        

        res = self.es.search(index=self.index,doc_type=self.type,\
                                body=q,scroll='10m',search_type='scan',\
                                _source_include=fields,size=500)
        si = res['_scroll_id']
        ct = res['hits']['total']
        return {'si':si,'ct':ct}

    def getMaxTime(self):
        q = {
            "aggs": {
                "max_time": {"max": {"field": "create_time"} }
            }
        }
        res = self.es.search(index=self.index,body=q,_source_include='*')
        res = res['aggregations']
        res = res['max_time']
        res = res['value']
        res = float(res)/1000.0
        res = datetime.datetime.fromtimestamp(res)
        res = res-datetime.timedelta(hours=8)
        return res

    def next(self,si):
        res = self.es.scroll(scroll_id=si,scroll='10m')
        si = res['_scroll_id']
        res = res['hits']['hits']
        res = [r['_source'] for r in res]
        return {'si':si,'rs':res}  

def initEsDocumentStore():
    prop = {}
    prop['HOST'] = '10.4.20.154'
    prop['PORT'] = 9200
    prop['INDEX'] = 'cut_data'
    prop['TYPE'] = 'cut_data'

    es = EsDocumentStore(prop)
    return es

def initEsDataStore():
    prop = {}
    prop['HOST'] = '10.4.21.59'
    prop['PORT'] = 9250
    prop['INDEX'] = 'data_group'
    prop['TYPE'] = 'data_group'

    es = EsDocumentStore(prop)
    return es

if __name__ == '__main__':

    print 'Hi'
    
    def test():
        es = initEsDocumentStore()
        x = es.getMaxTime()
        print x

    test()
